<template>
  <div class="skincare-container">
    <van-nav-bar title="护肤记录" left-arrow @click-left="goBack" />
    
    <div class="content">
      <!-- 今日护肤状态 -->
      <div class="today-status">
        <van-circle
          v-model:current-rate="todayProgress"
          :rate="100"
          :speed="100"
          :text="todayProgress + '%'"
          size="100px"
          layer-color="#ebedf0"
          color="linear-gradient(135deg, #667eea 0%, #764ba2 100%)"
        />
        <div class="status-text">
          <h3>今日护肤进度</h3>
          <p>{{ completedSteps }}/{{ totalSteps }} 步骤已完成</p>
        </div>
      </div>

      <!-- 护肤步骤列表 -->
      <div class="skincare-steps">
        <van-cell-group title="今日护肤步骤">
          <van-cell
            v-for="step in skincareSteps" 
            :key="step.id"
            :title="step.name"
            :label="step.description"
            :class="{ 'completed-step': step.completed }"
          >
            <template #icon>
              <van-icon
                :name="step.icon"
                size="24"
                :color="step.completed ? '#07c160' : '#969799'"
                style="margin-right: 12px;"
              />
            </template>
            <template #value>
              <van-checkbox
                v-model="step.completed"
                @change="updateProgress"
              />
            </template>
          </van-cell>
        </van-cell-group>
      </div>

      <!-- 产品使用记录 -->
      <div class="product-usage">
        <van-cell-group title="产品使用记录">
          <van-cell
            v-for="product in usedProducts"
            :key="product.id"
            :title="product.name"
            :label="`用量: ${product.amount} | ${product.notes}`"
          >
            <template #icon>
              <van-image
                width="40"
                height="40"
                :src="product.image"
                fit="cover"
                style="margin-right: 12px; border-radius: 8px;"
              />
            </template>
            <template #value>
              <van-tag type="primary">{{ product.category }}</van-tag>
            </template>
          </van-cell>
        </van-cell-group>
      </div>

      <!-- 添加产品使用 -->
      <div class="add-product-section">
        <van-button type="primary" block @click="showAddProduct = true">
          <van-icon name="plus" /> 记录产品使用
        </van-button>
      </div>

      <!-- 肌肤状态记录 -->
      <div class="skin-condition">
        <van-cell-group title="肌肤状态">
          <van-cell title="肌肤类型" :value="skinType" @click="showSkinTypePicker = true" />
          <van-cell title="肌肤问题" :value="skinIssuesText" @click="showSkinIssuePicker = true" />
          <van-cell title="肌肤状态评分" @click="showRatingDialog = true">
            <template #value>
              <van-rate v-model="skinRating" readonly size="14" />
            </template>
          </van-cell>
        </van-cell-group>
      </div>

      <!-- 护肤日记 -->
      <div class="skincare-diary">
        <van-cell-group title="护肤日记">
          <van-field
            v-model="diaryContent"
            rows="4"
            autosize
            type="textarea"
            maxlength="500"
            placeholder="记录今天的护肤感受、肌肤变化等..."
            show-word-limit
          />
          <div class="diary-actions">
            <van-button type="primary" size="small" @click="saveDiary">保存日记</van-button>
          </div>
        </van-cell-group>
      </div>
    </div>

    <!-- 添加产品弹窗 -->
    <van-dialog
      v-model:show="showAddProduct"
      title="记录产品使用"
      show-cancel-button
      @confirm="addProductUsage"
    >
      <van-field
        v-model="newProduct.name"
        label="产品名称"
        placeholder="请输入产品名称"
        required
      />
      <van-field
        v-model="newProduct.category"
        label="产品类别"
        placeholder="请选择产品类别"
        readonly
        @click="showCategoryPicker = true"
      />
      <van-field
        v-model="newProduct.amount"
        label="使用量"
        placeholder="请输入使用量"
      />
      <van-field
        v-model="newProduct.notes"
        label="使用感受"
        placeholder="记录使用感受"
        type="textarea"
        rows="2"
      />
    </van-dialog>

    <!-- 肌肤类型选择器 -->
    <van-popup v-model:show="showSkinTypePicker" position="bottom">
      <van-picker
        :columns="skinTypeOptions"
        @confirm="onSkinTypeConfirm"
        @cancel="showSkinTypePicker = false"
      />
    </van-popup>

    <!-- 肌肤问题选择器 -->
    <van-popup v-model:show="showSkinIssuePicker" position="bottom">
      <van-picker
        :columns="skinIssueOptions"
        @confirm="onSkinIssueConfirm"
        @cancel="showSkinIssuePicker = false"
      />
    </van-popup>

    <!-- 产品类别选择器 -->
    <van-popup v-model:show="showCategoryPicker" position="bottom">
      <van-picker
        :columns="categoryOptions"
        @confirm="onCategoryConfirm"
        @cancel="showCategoryPicker = false"
      />
    </van-popup>

    <!-- 评分弹窗 -->
    <van-dialog
      v-model:show="showRatingDialog"
      title="肌肤状态评分"
      show-cancel-button
      @confirm="saveSkinRating"
    >
      <div class="rating-content">
        <p>请为今天的肌肤状态评分：</p>
        <van-rate v-model="tempSkinRating" size="24" />
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { skincareApi } from '@/api/services'
import { initMqttClient, subscribeTopic, unsubscribeTopic, publishMessage } from '@/api/mqtt'

const router = useRouter()

// 基础数据
const todayProgress = ref(0)
const completedSteps = ref(0)
const totalSteps = ref(0)
const showAddProduct = ref(false)
const showSkinTypePicker = ref(false)
const showSkinIssuePicker = ref(false)
const showCategoryPicker = ref(false)
const showRatingDialog = ref(false)
const loading = ref(false)
const userId = ref(localStorage.getItem('userId') || '00000000-0000-0000-0000-000000000000')

// 肌肤数据
const skinType = ref('混合性肌肤')
const skinRating = ref(0)
const tempSkinRating = ref(0)
const skinIssues = ref([])
const diaryContent = ref('')

// 新使用产品数据
const newProduct = ref({
  name: '',
  category: '',
  amount: '',
  notes: ''
})

// 护肤步骤
const skincareSteps = ref([])

// 已使用产品
const usedProducts = ref([])

// 选项数据
const skinTypeOptions = [
  '油性肌肤', '干性肌肤', '混合性肌肤', '敏感性肌肤', '中性肌肤'
]

const skinIssueOptions = [
  '毛孔粗大', '黑头', '痘痘', '色斑', '皱纹', '松弛', '干燥', '出油', '敏感', '红血丝', '暗沉', '无特殊问题'
]

const categoryOptions = [
  '洁面', '爽肤水', '精华', '乳液', '面霜', '防晒', '面膜', '眼霜', '唇部护理', '其他'
]

// 计算属性
const skinIssuesText = computed(() => {
  return skinIssues.value.length > 0 ? skinIssues.value.join(', ') : '无特殊问题'
})

// 初始化数据
const initData = async () => {
  loading.value = true
  try {
    // 获取用户护肤数据
    const skincareResponse = await skincareApi.getSkincareByUserId(userId.value)
    if (skincareResponse && skincareResponse.length > 0) {
      const latestSkincare = skincareResponse[0]
      
      // 更新肌肤数据
      if (latestSkincare.skinType) skinType.value = latestSkincare.skinType
      if (latestSkincare.skinRating) skinRating.value = latestSkincare.skinRating
      if (latestSkincare.skinIssues) skinIssues.value = latestSkincare.skinIssues.split(',')
      if (latestSkincare.diaryContent) diaryContent.value = latestSkincare.diaryContent
      
      // 更新护肤步骤
      if (latestSkincare.steps && latestSkincare.steps.length > 0) {
        skincareSteps.value = latestSkincare.steps.map(step => ({
          id: step.id,
          name: step.name,
          description: step.description || '',
          icon: step.icon || 'gem-o',
          completed: step.isCompleted || false
        }))
      }
      
      // 更新使用产品
      if (latestSkincare.products && latestSkincare.products.length > 0) {
        usedProducts.value = latestSkincare.products.map(product => ({
          id: product.id,
          name: product.brand || '',
          category: product.category || '',
          amount: product.amount || '',
          notes: product.notes || '',
          image: product.photoUrl || 'https://img.yzcdn.cn/vant/cat.jpeg'
        }))
      }
      
      // 更新进度
      updateProgress()
    } else {
      // 初始化默认护肤步骤
      initializeDefaultSteps()
    }
  } catch (error) {
    console.error('获取护肤数据失败:', error)
    // 初始化默认护肤步骤
    initializeDefaultSteps()
  } finally {
    loading.value = false
  }
}

// 初始化默认护肤步骤
const initializeDefaultSteps = () => {
  skincareSteps.value = [
    {
      id: 1,
      name: '洁面',
      description: '温和清洁肌肤',
      icon: 'umbrella-circle-o',
      completed: false
    },
    {
      id: 2,
      name: '爽肤水',
      description: '调理肌肤pH值',
      icon: 'flower-o',
      completed: false
    },
    {
      id: 3,
      name: '精华',
      description: '针对性护理',
      icon: 'gem-o',
      completed: false
    },
    {
      id: 4,
      name: '乳液/面霜',
      description: '锁住水分',
      icon: 'bag-o',
      completed: false
    },
    {
      id: 5,
      name: '防晒',
      description: '日间防护',
      icon: 'sun-o',
      completed: false
    }
  ]
  updateProgress()
}

// MQTT消息处理
const handleMqttMessage = (message) => {
  console.log('收到MQTT消息:', message)
  if (message.type === 'skincare_update') {
    // 更新护肤数据
    if (message.skinType) skinType.value = message.skinType
    if (message.skinRating) skinRating.value = message.skinRating
    if (message.skinIssues) skinIssues.value = message.skinIssues.split(',')
    if (message.diaryContent) diaryContent.value = message.diaryContent
  }
}

// 初始化MQTT
const initMqtt = async () => {
  try {
    await initMqttClient()
    // 订阅用户专属主题
    subscribeTopic(`shelife/user/${userId.value}/skincare_update`, handleMqttMessage)
  } catch (error) {
    console.error('MQTT初始化失败:', error)
  }
}

// 方法
const goBack = () => {
  router.back()
}

const updateProgress = () => {
  const completed = skincareSteps.value.filter(step => step.completed).length
  const total = skincareSteps.value.length
  completedSteps.value = completed
  totalSteps.value = total
  todayProgress.value = total > 0 ? Math.round((completed / total) * 100) : 0
}

const addProductUsage = async () => {
  if (!newProduct.value.name.trim()) {
    showToast('请输入产品名称')
    return
  }
  
  try {
    // 准备保存的数据
    const productData = {
      userId: userId.value,
      brand: newProduct.value.name,
      category: newProduct.value.category,
      amount: newProduct.value.amount,
      notes: newProduct.value.notes,
      photoUrl: 'https://img.yzcdn.cn/vant/cat.jpeg'
    }
    
    // 调用API创建护肤产品记录
    const savedProduct = await skincareApi.createSkincare(productData)
    
    // 添加到列表
    const product = {
      id: savedProduct.id,
      name: savedProduct.brand || '',
      category: savedProduct.category || '',
      amount: savedProduct.amount || '',
      notes: savedProduct.notes || '',
      image: savedProduct.photoUrl || 'https://img.yzcdn.cn/vant/cat.jpeg'
    }
    
    usedProducts.value.push(product)
    resetNewProduct()
    
    showToast('产品使用记录已添加')
  } catch (error) {
    console.error('添加产品使用记录失败:', error)
    showToast('添加失败，请重试')
  }
}

const resetNewProduct = () => {
  newProduct.value = {
    name: '',
    category: '',
    amount: '',
    notes: ''
  }
}

const onSkinTypeConfirm = async (value) => {
  skinType.value = value
  showSkinTypePicker.value = false
  
  try {
    // 保存肌肤类型
    await saveSkincareData()
    showToast('肌肤类型已更新')
  } catch (error) {
    console.error('保存肌肤类型失败:', error)
    showToast('保存失败，请重试')
  }
}

const onSkinIssueConfirm = async (values) => {
  skinIssues.value = values
  showSkinIssuePicker.value = false
  
  try {
    // 保存肌肤问题
    await saveSkincareData()
    showToast('肌肤问题已更新')
  } catch (error) {
    console.error('保存肌肤问题失败:', error)
    showToast('保存失败，请重试')
  }
}

const onCategoryConfirm = (value) => {
  newProduct.value.category = value
  showCategoryPicker.value = false
}

const saveSkinRating = async () => {
  skinRating.value = tempSkinRating.value
  showRatingDialog.value = false
  
  try {
    // 保存肌肤评分
    await saveSkincareData()
    showToast('肌肤评分已保存')
  } catch (error) {
    console.error('保存肌肤评分失败:', error)
    showToast('保存失败，请重试')
  }
}

const saveDiary = async () => {
  if (!diaryContent.value.trim()) {
    showToast('请输入日记内容')
    return
  }
  
  try {
    // 保存护肤日记
    await saveSkincareData()
    showToast('护肤日记已保存')
  } catch (error) {
    console.error('保存护肤日记失败:', error)
    showToast('保存失败，请重试')
  }
}

// 保存护肤数据
const saveSkincareData = async () => {
  // 准备保存的数据
  const skincareData = {
    userId: userId.value,
    skinType: skinType.value,
    skinRating: skinRating.value,
    skinIssues: skinIssues.value.join(','),
    diaryContent: diaryContent.value,
    steps: skincareSteps.value.map(step => ({
      name: step.name,
      description: step.description,
      icon: step.icon,
      isCompleted: step.completed
    }))
  }
  
  // 调用API保存护肤数据
  const savedSkincare = await skincareApi.createSkincare(skincareData)
  
  // 发布MQTT消息
  publishMessage(`shelife/user/${userId.value}/skincare_update`, {
    type: 'skincare_update',
    skinType: skinType.value,
    skinRating: skinRating.value,
    skinIssues: skinIssues.value.join(','),
    diaryContent: diaryContent.value,
    timestamp: new Date().toISOString()
  })
  
  return savedSkincare
}

// 生命周期钩子
onMounted(() => {
  initData()
  initMqtt()
})

onUnmounted(() => {
  // 清理MQTT订阅
  unsubscribeTopic(`shelife/user/${userId.value}/skincare_update`, handleMqttMessage)
})
</script>

<style scoped lang="scss">
.skincare-container {
  min-height: 100vh;
  background: #f7f8fa;
  padding-bottom: 20px;
}

.content {
  padding: 0 16px;
}

.today-status {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin: 16px 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.status-text {
  h3 {
    margin: 0 0 8px 0;
    font-size: 18px;
    color: #333;
  }
  
  p {
    margin: 0;
    color: #666;
    font-size: 14px;
  }
}

.skincare-steps,
.product-usage,
.skin-condition,
.skincare-diary {
  margin-bottom: 16px;
}

.completed-step {
  background: #f0f9ff;
}

.add-product-section {
  margin: 16px 0;
}

.diary-actions {
  padding: 12px 16px;
  text-align: right;
}

.rating-content {
  padding: 20px;
  text-align: center;
  
  p {
    margin-bottom: 15px;
    color: #333;
  }
}
</style>